﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.IO;

namespace Tokenization
{
    public class CheckSpell
    {
        private Hashtable listReplace1, listReplace2;
        public CheckSpell(String path)
        {
            listReplace1 = getList(path + "/CheckSpell_Replace1.txt");
            listReplace2 = getList(path + "/CheckSpell_Replace2.txt");
        }
        private Hashtable getList(String filename)
        {
            Hashtable htb = new Hashtable();
            StreamReader sr = new StreamReader(filename);
            String line = "";
            while ((line = sr.ReadLine()) != null)
            {
                String[] l = line.Split('\t');
                if (!htb.ContainsKey(l[0])) htb.Add(l[0], l[1]);
            }
            sr.Close();
            return htb;
        }

        private String CheckSpell_Replace0(string text)
        {
            String patternI = @"([^\d])\.(\w)";
            String patternO = @"$1. $2";
            String pattern = @"([^\d])\.(\w)";
            return (new Rule(patternI, patternO, pattern)).ReplacePattern(text);
        }
        private String CheckSpell_Replace1(String text)
        {
            String res = text;
            foreach (String key in listReplace1.Keys)
            {
                res = res.Replace(key, (String)listReplace1[key]);
            }
            return res;
        }

        private String CheckSpell_Replace2(String text)
        {
            String res = text;
            foreach (String key in listReplace2.Keys)
            {
                if (res.IndexOf(key) >= 0)
                {
                    String patternI = key + "(\\s|\\W|$)";
                    String patternO = (String)listReplace2[key];
                    String pattern = key;
                    Rule rule = new Rule(patternI, patternO, pattern);

                    res = rule.ReplacePattern(res);
                }
            }

            return res;
        }

        public String Replace_CheckSpell(String text)
        {
            String res = text;
            res = CheckSpell_Replace0(res);
            res = CheckSpell_Replace1(res);
            res = CheckSpell_Replace2(res);
            return res;
        }
    }
}